package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

public class CacheClient {

    @Resource
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Objects value, Long time,TimeUnit unit){
        stringRedisTemplate.opsForValue()
                .set(key,JSONUtil.toJsonStr(value),time,unit);
    }


    public void setWithLogicalExpire(String key, Objects value, Long time,TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
    }

    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback,
            Long time,TimeUnit unit){
        String key = keyPrefix + id;
        //1.从redis中查询key
        String json  = stringRedisTemplate.opsForValue().get(key);

        //2.判断是否存在
        if(StrUtil.isNotBlank(json)){
            //3.存在直接返回
            return JSONUtil.toBean(json,type);
        }

        //是空串（注意空串和空值区别）返回
        if(json != null){
            return null;
        }
        //4.4成功则查询数据库
        R r = dbFallback.apply(id);
        //5.不存咋，返回
        if(r == null){
            //空值写入
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            //返回
            return null;
        }
        //6存在，写入redis

        this.set(key, (Objects) r, time, unit);
        //7.返回
        return r;
    }
}
